package com.zhh.front.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.zhh.common.enums.RCode;
import com.zhh.common.util.JwtUtil;
import com.zhh.front.view.RespResult;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //如果是OPTIONS,放行
        if("OPTIONS".equalsIgnoreCase(request.getMethod())){
            return true;
        }

        boolean requestSend = false;
        try {
            //2.获取token，进行验证
            String headerUid = request.getHeader("uid"); //请求头中的uid，和token中获取的uid进行比较，看是否一致
            String headerToken = request.getHeader("Authorization"); //取出请求头中Authorization开头的内容，token的值
            //查看token是否为空
            if(StringUtils.isNotBlank(headerToken)){

                String jwt = headerToken.substring(7);

                //读jwt
                Claims claims = JwtUtil.readJwt(jwt);

                //获取jwt中的数据，uid
                Integer jwtUid = claims.get("uid",Integer.class);

                //比较请求头中的uid，和token中获取的uid，是否一致
                if(headerUid.equals(String.valueOf(jwtUid))){
                    //token和发起请求的用户是同一个，请求通过
                    requestSend = true;
                }
            }
        } catch (Exception e) {
            requestSend = false;
            e.printStackTrace();
        }

        //token没有验证通过，需要给vue错误提示
        if( requestSend == false ){
            //返回json数据给前端
            RespResult result = RespResult.fail();
            result.setRCode(RCode.TOKEN_INVALID);

            //使用HttpServletResponse输出json,把token验证失败的消息告诉前端
            String respJson = JSONObject.toJSONString(result);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print(respJson);
            out.flush();
            out.close();
        }

        return requestSend;
    }
}
